#!/bin/bash

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright 2018 Brian Bennett <brian.bennett@joyent.com>

# Inspired by
# http://znogger.blogspot.com/2010/05/solaris-automatic-creation-of-home-dirs.html

# auto_homedir for use with illumos autofs to create user home directories on first access

if [[ -n "$TRACE" ]]; then
    export PS4='[\D{%FT%TZ}] ${BASH_SOURCE}:${LINENO}: ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
    set -o xtrace
fi

# Configurable variables
homebase='/home'        # Required
zpool='zones'           # Delete this if not using
delegated_base='data'   # Delete this if not using

# Set some reasonable restrictions on user zfs datasets
zfs_options='devices=off,setuid=off,snapshot_count=10'
zfs_local_allow='diff,mount,rollback,snapshot'
zfs_descendent_allow='clone,create,destroy,rename'

# Non-configurable variables
user="$1"
homedir="${homebase}/${user}"

##
## Exit early if possible
##

if ! [[ -d $homebase ]]; then
    : $homebase does not exist
    exit 0
fi
if [[ -d $homedir ]]; then
    : $homedir already exists
    exit 0
fi

# Get user details from passwd database
IFS=: read -r -a ent <<< $(getent passwd "$user")

if [[ -z ${ent[0]} ]]; then
    : User "$user" does not exist
    exit 0
fi
if ! [[ ${ent[5]} == $homedir ]]; then
    : "${ent[5]}" is not under "$homebase"
    exit 0
fi

# We've made it this far, it means the home directory needs to be created.

if [[ -n $zpool ]]; then
    zonename=$(zonename)
    case "$zonename" in
        global)
            zfsbase="${zpool:?}/home"
            ;;
        *)
            zfsbase="${zpool:?}/${zonename}/${delegated_base}/home"
            ;;
    esac
fi

# If $zfsbase exists create a child dataset, otherwise just make a directory.
if [[ -n $zfsbase ]] && [[ -d $zfsbase ]]; then
    zfs create -o "$zfs_options",mountpoint="$homedir" "${zfsbase}/${user}"
    zfs allow "$user" "$zfs_local_allow" "${zfsbase}/${user}"
    zfs allow -d "$user" "$zfs_descendent_allow" "${zfsbase}/${user}"
else
    mkdir "$homedir"
fi
# Populate initial contents of home directory
rsync -a /etc/skel/ "${homedir}/"
chown "${ent[2]}:${ent[3]}" "$homedir"

echo "localhost:$homedir"